﻿using System;
using System.ComponentModel;
using System.Linq;

namespace PocketBook.Model
{
    public class PropertySorter : ExpandableObjectConverter
    {
        public override bool GetPropertiesSupported(ITypeDescriptorContext context)
        {
            return true;
        }

        public override PropertyDescriptorCollection GetProperties(ITypeDescriptorContext context, object value, Attribute[] attributes)
        {
            var propertyDescriptors = TypeDescriptor.GetProperties(value, attributes);

            var propertyList = (from PropertyDescriptor propertyDescriptor in propertyDescriptors
                let attribute = (SortPriorityAttribute) propertyDescriptor.Attributes[typeof (SortPriorityAttribute)]
                select Tuple.Create(propertyDescriptor.Name, attribute == null ? 0 : attribute.SortPriority)).ToList();

            propertyList.Sort((a, b) =>
                              {
                                  var result = b.Item2 - a.Item2;
                                  return result == 0 ? a.Item1.CompareTo(b.Item1) : result;
                              });

            return propertyDescriptors.Sort(propertyList.Select(pair => pair.Item1).ToArray());
        }
    }
}